package ee.serge.client.content;

import java.util.List;

import com.google.gwt.event.logical.shared.HasValueChangeHandlers;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.user.client.ui.Composite;

import ee.serge.service.Service;
import ee.serge.shared.Loan;
import ee.serge.util.SimpleCallback;

public class LoansRequester extends Composite implements HasValueChangeHandlers<List<Loan>> {

   private static LoansRequester instance;
   private static boolean initialised = false;
   
   public static LoansRequester get() {
      if (instance == null) {
         instance = new LoansRequester();
         initialised = true;
      }
      return instance;
   }
   
   private EventBus bus;
   private long maxAmount = Long.MIN_VALUE;
   private long minAmount = Long.MAX_VALUE;
   private long minPeriod = 1;
   private long maxPeriod = Long.MIN_VALUE;
   private boolean loading;
   private List<Loan> loans;
   
   private LoansRequester() {
      requestLoans();
   }

   private void requestLoans() {
      loading = true;
      bus = new SimpleEventBus();
      Service.getPublicService().getLoans(new SimpleCallback<List<Loan>>() {
         @Override
         public void success(List<Loan> result) {
            for (Loan loan : result) {
               if (loan.getMaxLoan() > maxAmount) maxAmount = loan.getMaxLoan();
               if (loan.getMinLoan() < minAmount) minAmount = loan.getMinLoan();
               if (loan.getPeriod() > maxPeriod) maxPeriod = loan.getPeriod();
            }
            loans = result;
            loading = false;
            ValueChangeEvent.fire(LoansRequester.this, result);
         }
      });
   }
   
   public void refresh() {
      requestLoans();
   }
   
   @Override
   public void fireEvent(GwtEvent<?> event) {
      bus.fireEvent(event);
   }

   @Override
   public HandlerRegistration addValueChangeHandler(ValueChangeHandler<List<Loan>> handler) {
      return bus.addHandler(ValueChangeEvent.getType(), handler);
   }

   public static LoansRequester getInstance() {
      return instance;
   }

   public EventBus getBus() {
      return bus;
   }

   public long getMaxAmount() {
      return maxAmount;
   }

   public long getMinAmount() {
      return minAmount;
   }

   public long getMinPeriod() {
      return minPeriod;
   }

   public long getMaxPeriod() {
      return maxPeriod;
   }

   public boolean isLoading() {
      return loading;
   }

   public List<Loan> getLoans() {
      return loans;
   }

   public static boolean isInitialised() {
      return initialised;
   }

}
